<?
  require_once('../db.php');
  db_connect();

  $id = intval($_GET["id"]);
  $w = intval($_GET["w"]);
  $h = intval($_GET["h"]);
  $pn = intval($_GET["pn"]);
  if ($pn !== 1 && $pn !== 2)
    $pn = 1;
  if ($w < 64 || $h < 64) {
    $w = 64;
    $h = 64;
  }

  $query = 'SELECT id_TPT AS id, photo'.$pn.'_TPT as photo';
  $query .= ' FROM v_tpt_non_ver';
  $query .= ' WHERE id_TPT = '.$id;
  // $query .= ' ORDER BY id_TPT';
  $result = mysql_query($query) or die("ERROR PERFORMING QUERY '".$query."': ".mysql_error());

  if ($row = mysql_fetch_assoc($result))
    $photopath = $row["photo"];
  else {
    echo "Invalid place ID";
    mysql_free_result($result);
    exit;
  }

  mysql_free_result($result);

  $url = 'http://intranet.letsdoitromania.ro'.$photopath;
  // $url = '../..'.$photopath;
  $img = imagecreatefromjpeg($url);
  $iw = imagesx($img);
  $ih = imagesy($img);

  // TODO rotate image

  $sx = 1.0;
  if ($w < $iw)
    $sx = doubleval($w)/$iw;
  $sy = 1.0;
  if ($h < $ih)
    $sy = doubleval($h)/$ih;

  // scale maximum
  $sm = min($sx, $sy);
  $nw = doubleval($iw)*$sm;
  $nh = doubleval($ih)*$sm;

  // content type
  header('Content-type: image/jpeg');
  $newimg = imagecreatetruecolor($nw, $nh);
  imagecopyresampled($newimg, $img, 0, 0, 0, 0, $nw, $nh, $iw, $ih);
  imagejpeg($newimg);
?>
